
<template>
  <div class="target_setting_container">
    <template>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        
        <!-- 总服务部 -->
        <el-tab-pane label="总服务部" name="serviceDepartment">
          <div class="search_box">
            <div v-if="powerList.departmentAdd.show == 1" class="btn btn_add" @click="showPopup('ruleForm')">
              <i class="el-icon-plus"></i>
              <span class="btn_txt">新增</span>
            </div>

            <div class="btn btn_search fr" @click="searchDeartmentData(searchFormServiceDepartment)">
              <span class="btn_txt">查询</span>
            </div>

            <div class="fr">
              <el-form :model="searchFormServiceDepartment" :inline="true" class="searchFormServiceDepartment">
                <el-form-item size="small">
                  <el-select  style="width:230px;" multiple collapse-tags v-model="searchFormServiceDepartment.schoolIdList" placeholder="选择校区(多选)">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:195px;"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="searchFormServiceDepartment.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="clear"></div>
          </div>

          <div class="table_box">
            <adminTable :tableHead="tableHeadServiceDepartment" :tableData="tableDataServiceDepartment"></adminTable>
            <el-pagination
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageDepartment.curPage"
              :page-sizes="[10, 20, 50]"
              :page-size="pageDepartment.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageDepartment.totalRows">
            </el-pagination>
          </div>
        </el-tab-pane>
        <!-- 总服务部 end -->

        <!-- 年度 -->
        <el-tab-pane label="年度" name="year">
          <div class="search_box">
            <div v-if="powerList.yearAdd.show == 1" class="btn btn_add" @click="showPopupYear('ruleForm')">
              <i class="el-icon-plus"></i>
              <span class="btn_txt">新增</span>
            </div>

            <div class="btn btn_search fr" @click="searchYearData(searchFormYear)">
              <span class="btn_txt">查询</span>
            </div>

            <div class="fr">
              <el-form :model="searchFormYear" :inline="true" class="searchFormYear">
                <el-form-item size="small">
                  <el-select @change="changeSchool" clearable style="width:230px;" v-model="searchFormYear.schoolId" placeholder="选择校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:195px;"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="searchFormYear.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small">
                  <el-select @change="changeCourse" clearable style="width:120px;" v-model="searchFormYear.courseId" placeholder="大类">
                    <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item size="small">
                  <el-select  style="width:120px;" clearable v-model="searchFormYear.productId" placeholder="课程产品">
                    <el-option v-for="(item,key) in searchFormProductList" :key="key" :label="item.productName" :value="item.productId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="clear"></div>
          </div>

          <div class="tab_box">
            <div class="btn_tab fl" @click="clickTab(0)" :class="{'isActive' : tab_id == 0}">按人次</div>
            <div class="btn_tab fl" @click="clickTab(1)" :class="{'isActive' : tab_id == 1}">按金额</div>
            <!-- <div class="btn_tab fl" @click="clickTab(2)" :class="{'isActive' : tab_id == 2}">不限</div> -->
            <div class="clear"></div>
          </div>

          <div class="table_box year_box">
            <div class="table_title" v-html="tableYearTitle"></div>
            <!-- 不限 -->
            <adminTable v-show="tab_id == 2" :tableHead="tableHeadYearAll" :tableData="tableDataYearAll"></adminTable>
            <!-- 不限 -->
            <!-- 金额 / 人次 -->
            <adminTable v-show="tab_id !== 2" :tableHead="tableHeadYear" :tableData="tableDataYear"></adminTable>
            <!-- 金额 / 人次 -->
            <el-pagination
              class="pagination"
              @size-change="handleSizeChangeYear"
              @current-change="handleCurrentChangeYear"
              :current-page="pageYear.curPage"
              :page-sizes="[5, 20, 50]"
              :page-size="pageYear.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageYear.totalRows">
            </el-pagination>
          </div>
        </el-tab-pane>
        <!-- 年度 end-->

    
        <!-- 月度 -->
        <el-tab-pane label="月度" name="monthly">
          <div class="search_box">
            <!-- <div v-if="powerList.monthAdd.show == 1" class="btn btn_add" @click="showPopupMonth('ruleForm')">
              <i class="el-icon-plus"></i>
              <span class="btn_txt">新增</span>
            </div> -->
            <div v-if="powerList.monthAdd.show == 1" class="btn btn_add" @click="showPopupMonth('ruleForm')">
              <i class="el-icon-plus"></i>
              <span class="btn_txt">新增</span>
            </div>

            <div class="btn btn_search fr" @click="searchMonthData(searchFormMonthly)">
              <span class="btn_txt">查询</span>
            </div>

            <div class="fr">
              <el-form :model="searchFormMonthly" :inline="true" class="searchFormMonthly">
                <el-form-item size="small">
                  <el-select @change="(e) => changeMonthSchool(e, false, 'all')" clearable style="width:150px;" v-model="searchFormMonthly.schoolId" placeholder="选择校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:130px;"
                    value-format="yyyy"
                    format="yyyy年"
                    v-model="searchFormMonthly.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small">
                  <el-date-picker
                    style="width:90px;"
                    value-format="MM"
                    format="M月"
                    v-model="searchFormMonthly.financialMonth"
                    type="month"
                    placeholder="月份">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small">
                  <el-select @change="changeCourse" clearable style="width:120px;" v-model="searchFormMonthly.courseId" placeholder="大类">
                    <el-option v-for="(item,key) in courseList" :key="key" :label="item.courseName" :value="item.courseId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-select  style="width:120px;" clearable v-model="searchFormMonthly.productId" placeholder="课程产品">
                    <el-option v-for="(item,key) in searchFormProductList" :key="key" :label="item.productName" :value="item.productId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small">
                  <el-select style="width:100px;" clearable  v-model="searchFormMonthly.employeesId" placeholder="员工">
                    <el-option v-for="(personItem,key) in personList" :key="key" :label="personItem.employeesName" :value="personItem.employeesId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="clear"></div>
          </div>

          <div class="table_box month_box">
            <adminTable :tableHead="tableHeadMonth" :tableData="tableDataMonth" :weekIndex="showMonthWeekData" :maxWeekNum="maxWeekNum"></adminTable>
            <el-pagination
              class="pagination"
              @size-change="handleSizeChangeMonth"
              @current-change="handleCurrentChangeMonth"
              :current-page="pageMonth.curPage"
              :page-sizes="[5, 20, 50]"
              :page-size="pageMonth.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageMonth.totalRows">
            </el-pagination>
          </div>
        </el-tab-pane>
        <!-- 月度 end-->

      </el-tabs>
    </template>

    <!-- 总服务部弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatusService">
        <div class="popup mini">
          <i class="el-icon-error icon_close" @click="popupState.showStatusService = false"></i>
          <div class="title">{{popupState.popupNameService}}</div>

          <div class="content">
            <el-form :model="formDataServiceDepartment" ref="departmentRuleForm" :rules="departmentRules" label-position="left"  style=""
              label-width="90px" class="form">
              <div style="overflow:hidden">
                <el-form-item size="small not_must" label="校区 : " style="width: 100%" prop="schoolId">
                  <el-select @change="changeSchool" v-model="formDataServiceDepartment.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small" label="学年 : " style="width: 100%" prop="financialYear">
                  <el-date-picker
                    style="width: 100%"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="formDataServiceDepartment.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small" label="业绩目标 : " style="width: 100%" prop="targetAchievement">
                  <el-input v-model="formDataServiceDepartment.targetAchievement"  placeholder="请输入年度业绩目标（元）"></el-input>
                </el-form-item>


              </div>

            </el-form>

            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupNameService == '新增'" @click="insertDepartment('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupNameService == '编辑'" @click="updateDepartment('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
      </div>
    </transition>
    <!-- 总服务部弹窗 -->

    <!-- 年度弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatusYear">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="popupState.showStatusYear = false"></i>
          <div class="title">{{popupState.popupNameYear}}</div>

          <div class="content">
            <el-form :model="formDataYear" ref="yearRules" :rules="yearRules" label-position="left"  style=""
              label-width="90px" class="form">
              <div style="overflow:hidden">
                <el-form-item size="small" prop="schoolId" class="fl" label="校区选择 : " style="width: 40%; margin-bottom: 15px;">
                  <el-select @change="changeSchool" v-model="formDataYear.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in powerSchoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small" prop="financialYear" class="fl" label="学年 : " style="width: 30%;margin-bottom: 15px;">
                  <el-date-picker
                    style="width:195px;"
                    @change="changeYear"
                    value-format="yyyy"
                    :format="computedYear"
                    v-model="formDataYear.financialYear"
                    type="year"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <div class="clear"></div>

                <div class="tab_box" style="padding-left: 2px;">
                  <!-- <div class="btn_tab fl" @click="clickYearTab(0)" :class="{'isActive' : year_tab_id == 0}">按人次</div>
                  <div class="btn_tab fl" @click="clickYearTab(1)" :class="{'isActive' : year_tab_id == 1}">按金额</div> -->
                  <span @click="addProduct" class="addProduct" v-if="popupState.popupNameYear == '新建年度目标'">添加课程</span>
                  <div class="clear"></div>
                </div>

                <div class="edit_table_box">
                  <!-- <div v-if="year_tab_id == 0">
                    <eidtTable :tableHead="tableHeadPeople" :tableData="tableDataPeople"></eidtTable>
                  </div>
                  <div v-if="year_tab_id == 1">
                    <eidtTable :tableHead="tableHeadMoney" :tableData="tableDataMoney"></eidtTable>
                  </div> -->

                  <eidtTable :tableHead="tableHeadAdd" :tableData="tableDataAdd"></eidtTable>

                  <div class="btn_box">
                    <div class="btn btn_add" v-if="popupState.popupNameYear == '新建年度目标'" @click="submitAddYear('ruleForm')">
                      <span class="btn_txt">保存</span>
                    </div>

                    <div class="btn btn_add" v-if="popupState.popupNameYear == '编辑年度目标'" @click="submitEditYearPeople('ruleForm')">
                      <span class="btn_txt">保存</span>
                    </div>
                  </div>
                </div>


              </div>

            </el-form>

            <!-- <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupNameYear == '新建'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupNameYear == '编辑'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div> -->

          </div>
        </div>
      </div>
    </transition>
    <!-- 年度弹窗 -->

    <!-- 月度弹窗 -->
    <transition name="el-fade-in-linear">
      <monthPopup 
        :formDataMonth="formDataMonth" 
        :popupState="popupState" 
        :isUpdateMonth="isUpdateMonth"
        :isAdd="isAdd"
        @updateMonthData="updateMonthData" 
        @updateMonthStatusNum="updateMonthStatusNum" 
        ></monthPopup>
    </transition>
    <!-- 月度弹窗 -->
  </div>
</template>


<style>



  .target_setting_container .month_table .month_table_info{
    padding: 10px 0 10px 20px;
    width: 100%;
    box-sizing: border-box;
    background: #F5F7FA;
  }
  .target_setting_container .month_table td {
    background: #F5F7FA;
    border-bottom: 1px solid #EBEEF5;
  }
  .target_setting_container .month_table .el-tooltip, 
  .target_setting_container .month_table .edit-cell
  {
    background: #fff;
    border-radius: 4px;
  }

  .target_setting_container .month_table tbody tr td:first-child .el-tooltip {
    background: #F0F2F5 !important;
  }

  .target_setting_container .month_table .cell {
    /* color: #000; */
  }
  

  .target_setting_container .el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #F0F2F5;
  }
  .target_setting_container .year_box .el-table__row td:first-child,
  .target_setting_container .year_box thead tr th:first-child {
    background: #F5F7FA !important;
  }
  .year_box .el-table__fixed-footer-wrapper tbody td {
    background: #F5F7FA !important;
  }
  .year_box .el-table__fixed-footer-wrapper tbody td:first-child .cell {
    color: #FC8434 !important;
  }
  
  .year_box .el-table__footer-wrapper td {
    background: #F5F7FA !important;
  }
  .target_setting_container .table_box {
    box-shadow: none;
  }
  .target_setting_container .el-tabs__nav {
    background: #fff;
  }
  .target_setting_container .el-tabs__header {
    margin-bottom: 0;
  }
  .target_setting_container .el-tabs__content {
    box-shadow: 2px 2px 8px 4px rgba(213,212,212,0.5);
    padding-top: 15px;
    box-sizing: border-box;
    background: #fff;
  }
  .target_setting_container .el-tabs--card>.el-tabs__header .el-tabs__nav {
    /* border-bottom: 1px solid #E4E7ED; */
    border-radius: 3px 3px 0 0;
  }
  .target_setting_container .el-tabs__item {
    height: 35px;
    line-height: 35px;
    border-bottom: 1px solid #E4E7ED !important;
  }
  .target_setting_container .el-tabs__content{
    border-left: 1px solid #E4E7ED;
  }

  .target_setting_container .el-tabs__item.is-active {
    color: #FC8434;
    border-bottom: 1px solid #fff !important;
  }
  .month_popup  .el-tabs__item {
    height: 50px !important;
    /* line-height: 60px !important; */
    padding: 0 5px !important;
    font-size: 12px;
    border-bottom: none !important;
  }
  .month_popup .el-tabs--left.el-tabs--card .el-tabs__item.is-left.is-active {
    border-right-color: #E4E7ED;
    /* background: #EFF0F2; */
  }
  .month_popup  .el-tabs__item.is-active {
    border-bottom: none !important;
  }
</style>
<style scoped>


.month_table_item{
  margin-bottom: 25px;
  position: relative;
}
.month_table .month_table_item:last-child {
  margin-bottom: 0;
}
.addMonth{
  cursor: pointer;
  color: #77A4FF;
  text-align: right;
  padding: 10px 0;
  float: right;
}
.deleteMonth{
  position: absolute;
  right: 10px;
  top: 0;
}
.addProduct {
  cursor: pointer;
  line-height: 25px;
  color: #77A4FF;
}
.tab_box{
  padding-left: 15px;
  margin-bottom: 10px;
}

.table_box .table_title {
  background: #F5F7FA;
  text-align: right;
  height: 30px;
  line-height: 30px;
  color: #77A4FF;
  font-size: 12px;
  padding-right: 20px;
}

.tab_box .btn_tab.isActive {
  background: #77A4FF;
  color: #fff;
}
.tab_box .btn_tab {
  width:70px;
  height:25px;
  line-height: 25px;
  margin-right: 15px;
  color: #77A4FF;
  font-size: 12px;
  cursor: pointer;
  text-align: center;
  border: 1px solid #77A4FF;
  border-radius:15px;
}
.tab_box .btn_tab:hover {
  background: #77A4FF;
  color: #fff;
}

.btn_search {
  padding: 0 20px;
  text-align: center;
  height: 32px;
  font-size: 12px;
  background: #FBA56C;
  line-height: 32px;
}
.search_box {
  padding: 0 15px;
  box-sizing: border-box;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable';
import monthPopup from './targetSetting_monthPopup'
import eidtTable from '@/components/assembly/eidtTable'
import {
  createNamespacedHelpers,
  // mapState,
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("targetSetting");



export default {
  name: 'targetSetting',
  data() {
    return {
      activeName: 'serviceDepartment',
      activeName_month: 'tab0',
      formDataMonth: {
        schoolId: '',
        financialYear: '',
        financialMonth: '',
        // yearTargetPeople: '',
        // yearTargetPrice: '',
        periodsList: [
          // 每一期
          {
            periodsItem: [      // 每一期里的所有数据集合
              
            ],
            
          },
        ]
        // productId: '',
        // employeesId: '',
        
      },
      powerList: {
        departmentAdd: {
          show: 0,
          menuId: ''
        },
        yearAdd: {
          show: 0,
          menuId: ''
        },
        monthAdd: {
          show: 0,
          menuId: ''
        },
      },
      powerSchoolList: [],
      weekNum: 1,               // 每月自然周数
      weekDateArr: [],
      tab_id: 0,
      year_tab_id: 0,
      schoolName: '',
      titleSchoolName: '',
      tableYearTitle: '单位 : 人',

      productId: '',
      productName: '',
      showAddProduct: false,

      searchFormServiceDepartment: {
        schoolId: '',
        schoolIdList: [],
        financialYear: '',
      },
      searchFormYear: {
        schoolId: '',
        financialYear: '',
        courseId: '',
        productId: '',
      },
      searchFormMonthly: {
        schoolId: '',
        financialYear: '',
        financialMonth: '',
        courseId: '',
        productId: '',
      },

      formDataServiceDepartment: {
        schoolIdList: [],
        schoolId: '',
        financialYear: '',
        targetAchievement: '',
      },
      formDataYear: {
        financialYear: '',
        schoolId: '',
      },

      popupState: {
        showStatusService: false,
        popupNameService: '新增',

        showStatusYear: false,
        popupNameYear: '新建',

        showStatusMonthly: false,
        popupNameMonthly: '新建月度目标',
      },

      // 总服务部 列表 table
      tableHeadServiceDepartment: {   
        // border: true,
        // order: true,
        operation_width: '150px',
        setFunction: [
          {
            // showState: "0",
            // hideKey: "flag",
            fun: this.tableEditDepartment,
            name: "编辑"
          },
          // {
          //   fun: this.tableLogDepartment,
          //   name: "日志"
          // },
        ],
        data: [
          {
            name: '校区',
            key: 'schoolName',
            align: 'center',
          },
          {
            name: "学年",
            key: "financialYear",
            align: "center",
          },
          {
            name: "指导业绩目标(元)",
            key: "targetAchievement",
            align: "center",
            width: '',
          },
          {
            name: "校区业绩目标(元)",
            key: "cumulativeComplete",
            align: "center",
            width: '',
          },
          {
            name: "创建时间",
            key: "createTime",
            align: "center",
          },
        ]
      },
      tableDataServiceDepartment: [],
      pageDepartment: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      pageYear: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      pageMonth: {
        curPage: 1,
        pageSize: 5,
        totalRows: 0,
      },
      departmentRules: {
        schoolId: [
          { required: false, message: '请选择校区', trigger: 'change' },
        ],
        financialYear: [
          { required: true, message: '请选择学年', trigger: 'change' },
        ],
        targetAchievement: [
          { required: true, message: '请输入业绩目标', trigger: 'blur' },
        ],
      },

      // 年度 列表 table
      powerYearSchoolList: [],
      tableHeadYear: {
        operation_width: '150px',
        border: true,
        summary: true,
        stripe: true,
        setFunction: [
          {
            // showState: "0",
            // hideKey: "flag",
            fun: this.tableEditYear,
            name: "编辑"
          },
          // {
          //   fun: this.tableLog,
          //   name: "日志"
          // },
        ],
        data: [
          {
            name: '课程产品',
            key: 'productName',
            align: 'center',
            fixed: true,
            width: '150',
          },
          {
            name: '学年(年)',
            key: 'financialYear',
            align: 'center',
            fixed: true
          },
          {
            name: "9月",
            key: "sep",
            align: "center",
          },
          {
            name: "10月",
            key: "oct",
            align: "center",
          },
          {
            name: "11月",
            key: "nov",
            align: "center",
          },
          {
            name: "12月",
            key: "dec",
            align: "center",
          },
          {
            name: "1月",
            key: "jan",
            align: "center",
          },
          {
            name: "2月",
            key: "feb",
            align: "center",
          },
          {
            name: "3月",
            key: "mar",
            align: "center",
          },
          {
            name: "4月",
            key: "apr",
            align: "center",
          },
          {
            name: "5月",
            key: "may",
            align: "center",
          },
          {
            name: "6月",
            key: "jun",
            align: "center",
          },
          {
            name: "7月",
            key: "jul",
            align: "center",
          },
          {
            name: "8月",
            key: "aug",
            align: "center",
          },
        ]
      },
      tableDataYear: [],

      tableHeadYearAll: {
        border: true,
        edit: false,
        setFunction: [
          {
            fun: this.tableEditYearAll,
            name: "编辑"
          },
        ],
        data: [
          {
            name: "课程产品",
            key: "productName",
            align: 'center',
            width: '200px',
            fixed: true
          },
          
          {
            name: "9月",
            key: "sep",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "10月",
            key: "oct",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "11月",
            key: "nov",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "12月",
            key: "dec",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "1月",
            key: "jan",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "2月",
            key: "feb",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "3月",
            key: "mar",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "4月",
            key: "apr",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "5月",
            key: "may",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "6月",
            key: "jun",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "7月",
            key: "jul",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          },
          {
            name: "8月",
            key: "aug",
            align: 'center',
            children: [
              {
                name: "人次",
                key: "monthTargetNumber",
                align: 'center',
                type: 'el-input'
              },
              {
                name: "金额",
                key: "monthTargetPrice",
                align: 'center',
                type: 'el-input'  
              },
            ]
          }, 
        ]
      },
      tableDataYearAll: [],


      tableHeadAdd: {
        border: true,
        edit: false,
        data: [
          
          
        ]
      },
      tableDataAdd: [
        
      ],

      yearRules: {
        schoolId: [
          { required: false, message: '请输入校区名称', trigger: 'blur' },
        ],
        financialYear: [
          { required: false, message: '请选择校区所在省份', trigger: 'change' },
        ],
      },


      // 月度 列表 table
      tableHeadMonth: {
        operation_width: '150px',
        border: true,
        setFunction: [
          {
            showState: "0",
            hideKey: "isTotal",
            fun: this.tableEditMonth,
            name: "编辑"
          },
          {
            showState: "0",
            hideKey: "isTotal",
            fun: this.tableDeleteMonth,
            name: "删除"
          },
        ],
        data: [
          {
            name: '员工姓名',
            key: 'personName',
            align: 'center',
            fixed: true,
          },
          {
            name: "工号",
            key: "workNo",
            align: "center",
            fixed: true
          },
          {
            name: "校区",
            key: "schoolName",
            align: "center",
            fixed: true
          },
          {
            name: "课程产品",
            key: "productName",
            align: "center",
            width: '100px',
          },
          {
            name: '第一周',
            key: "week",
            align: "center",
            children: [
              {
                name: "目标业绩(元)",
                key: "weekTargetPrice",           // 报错地点
                align: 'center',
                // width: '55px'
              },
              {
                name: "签单人数(人)",
                key: "fullNumber",
                align: 'center',
                width: '55px'
              },
              {
                name: "定金人数(人)",
                key: "earnestNumber",
                align: 'center',
                width: '55px'
              },
              {
                name: "试听人数(人)",
                key: "auditionNumber",
                align: 'center',
                width: '55px'
              },
              {
                name: "有效单数(人)",
                key: "effectiveSingular",
                align: 'center',
                width: '55px'
              },
            ],
            setFunction: [
              {
                fun: this.prevWeek,
                name: "上一期"
              },
              {
                fun: this.nextWeek,
                name: "下一期"
              },
            ]
          },
          {
            name: "本月小计",
            key: "subtotal",
            align: "center",
            children: [
              {
                name: "目标业绩(元)",
                key: "weekTargetPrice",           
                align: 'center',
                // width: '50px'
              },
              {
                name: "签单人数(人)",
                key: "fullNumber",
                align: 'center',
                width: '50px'
              },
              {
                name: "定金人数(人)",
                key: "earnestNumber",
                align: 'center',
                width: '50px'
              },
              {
                name: "试听人数(人)",
                key: "auditionNumber",
                align: 'center',
                width: '50px'
              },
              {
                name: "有效单数(人)",
                key: "effectiveSingular",
                align: 'center',
                width: '50px'
              },
            ],
          },
          
        ]
      },
      tableDataMonth: [
      ],

      tableHead_editMonth: {
        data: [
          {
            name: '',
            key: 'weekName',
            align: 'center',
            disabled: true
          },
          {
            name: '目标业绩(元)',
            key: 'weekTargetPrice',
            align: 'center',
          },
          // {
          //   name: '全款金额(元)',
          //   key: 'fullPrice',
          //   align: 'center',
          // },
          {
            name: '签单人数(人)',
            key: 'fullNumber',
            align: 'center',
          },
          // {
          //   name: '定金金额(元)',
          //   key: 'earnestPrice',
          //   align: 'center',
          // },
          {
            name: '定金人数(人)',
            key: 'earnestNumber',
            align: 'center',
          },
          {
            name: '试听人数(人)',
            key: 'auditionNumber',
            align: 'center',
          },
          {
            name: '有效单数(人)',
            key: 'effectiveSingular',
            align: 'center',
          },
        ]
      },
      tableData_editMonth: [
        {
          weekName: '第一周',
          sort: 0,
        },{weekName: '第二周',sort: 1,},{weekName: '第三周',sort: 2},{weekName: '第四周',sort: 3}
      ],
      isUpdateMonth: 0,
      isAdd: 0,

      
      monthRules: {
        schoolId: [
          { required: false, message: '请输入校区名称', trigger: 'blur' },
        ],
        productId: [
          { required: false, message: '请输入校区名称', trigger: 'blur' },
        ],
        financialYear: [
          { required: false, message: '请选择校区所在省份', trigger: 'change' },
        ],
        financialMonth: [
          { required: false, message: '请选择校区所在城市', trigger: 'change' },
        ],
        employeesId: [
          { required: false, message: '请选择校区所在城市', trigger: 'change' },
        ],
      },
      powerMonthSchoolList: [],
      


      rules: {
        schoolName: [
          { required: true, message: '请输入校区名称', trigger: 'blur' },
        ],
        provinceCode: [
          { required: true, message: '请选择校区所在省份', trigger: 'change' },
        ],
        cityCode: [
          { required: true, message: '请选择校区所在城市', trigger: 'change' },
        ],
      },
      
      schoolList: [],
      departmentPowerSchoolList: [],
      yearPowerSchoolList: [],
      monthPowerSchoolList: [],


      productList: [
        {
          productId: '1',
          productName: 'AA'
        }
      ],
      courseList: [],
      personList: [],
      searchFormProductList: [],
      workNo: '',
      employeesName: '',

      targetYearChildId: {},
      showMonthWeekData: 0,
      maxWeekNum: 5,
      
    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    
    this.initSchoolList();
    this.initProductList();
    this.queryAllCourseType();    // 查询所有大类

    if(sessionStorage.getItem('settingTabName')) {
      this.activeName = sessionStorage.getItem('settingTabName');
    }else{
      this.activeName = 'serviceDepartment';
    }

    // console.log(this.vuexDepartmentSearchForm)
    if(this.vuexDepartmentSearchForm) {
      this.searchFormServiceDepartment = this.vuexDepartmentSearchForm
    }
    if(this.vuexYearSearchForm) {
      this.searchFormYear = this.vuexYearSearchForm
    }
    if(this.vuexMonthSearchForm) {
      this.searchFormMonthly = this.vuexMonthSearchForm
    }


    this.initYearData();
    this.initMonthData();
    this.initServiceDepartmentData();



  },
  watch: {
    
    
  },
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    initSchoolList(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        
        if(btnId) {
          this.powerSchoolList = res
          this.formDataMonth.schoolId = this.powerSchoolList[0].schoolId
          if(this.activeName == 'monthly') {
            this.changeMonthSchool(this.formDataMonth.schoolId)
          }
          
        }else{
          this.schoolList = res
        }

        if(this.activeName == 'serviceDepartment') {
          this.initServiceDepartmentData();
        }
        // this.schoolList = res;
        // this.powerSchoolList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    initProductList() {
      this.formGet({
        API: 'queryProductByCourseId',
        data: {
          courseId: '',
        }
      }).then(res => {
        this.productList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    

    changeSchool(e) {
      this.schoolList.forEach(item => {
        if(item.schoolId == e) {
          this.schoolName = item.schoolName;
          this.titleSchoolName = item.schoolName;
        }
      })
    },


  /* ========================= 总服务部START =========================== */
    searchDeartmentData(searchFormServiceDepartment) {
      this.pageDepartment.curPage = 1;
      this.updateInfo(["vuexDepartmentSearchForm", searchFormServiceDepartment])
      this.initServiceDepartmentData(searchFormServiceDepartment)
    },
    initServiceDepartmentData(searchForm) {
      let searchValue = searchForm || this.searchFormServiceDepartment || '';
      let data = {}
      Object.assign(data, searchValue);
      
      data.curPage = this.pageDepartment.curPage;
      data.pageSize = this.pageDepartment.pageSize;
  
      if(data.schoolIdList[0] == '' || data.schoolIdList.length == 0) {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId)
        });
        data.schoolId = arr;
      }else{
        data.schoolId = this.searchFormServiceDepartment.schoolIdList
      }

      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;
      
      
      this.post({
        API: 'selectBmTargetServicesPageList',
        data: data
      }).then(res => {
        this.tableDataServiceDepartment = res.data;

        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '总服务部') {
            item.children.forEach(childItem => {
              if(childItem.label == '新增') {
                this.powerList.departmentAdd.show = 1
                this.powerList.departmentAdd.menuId = childItem.menuId
              }
            })
          }
        })
        this.pageDepartment = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
       
    },

    showPopup(formName) {
      this.$refs.departmentRuleForm.resetFields();   // 初始化

      this.popupState = {
        showStatusService: true,
        popupNameService: '新增',
      }
    },

    insertDepartment() {
      let data = this.formDataServiceDepartment;
      data.schoolName = this.schoolName;
      // data.schoolId = data.schoolId.join(',')

      this.$refs['departmentRuleForm'].validate((valid) => {
        if (valid) {
          this.post({
            API: 'insertDepartment',
            data: data
          }).then(res => {
            this.$message.success('新增成功');
            this.popupState.showStatusService = false;
            this.initServiceDepartmentData();
          }).catch(err => {
            this.$message.error(err);
          })
        }
      });
    },

    tableEditDepartment(rowData) {
      this.$refs.departmentRuleForm.resetFields();
      this.formGet({
        API: 'selectByIdDepartment',
        data: {
          id: rowData.row.targetServicesId
        }
      }).then(res => {
        this.formDataServiceDepartment = res;
        this.popupState = {
          showStatusService: true,
          popupNameService: '编辑',
        }
      }).catch(err => {
        this.$message.error(err);
      })

      
    },

    // 编辑提交
    updateDepartment() {
      let data = this.formDataServiceDepartment
      data.schoolName = this.schoolName;
      data.dataId = this.formDataServiceDepartment.targetServicesId
      this.$refs['departmentRuleForm'].validate((valid) => {
        if (valid) {
          this.post({
            API: 'updateDepartment',
            data: data
          }).then(res => {
            this.$message.success('修改成功');
            this.popupState.showStatusService = false;
            this.initServiceDepartmentData();
          }).catch(err => {
            this.$message.error(err);
          })
        }
      });
    },

    handleClick(tab, event) {
      // console.log(tab, event);
      sessionStorage.setItem('settingTabName', tab.name)
      switch (tab.name) {
        case 'serviceDepartment':
          this.initServiceDepartmentData();
          break;
        case 'year':
          this.initYearData();
          break;
        case 'monthly':
          this.initMonthData();
          break;
      
        default:
          break;
      }
      
    },
    

    

    tableEdit(rowData) {

    },

    tableLog(rowData) {

    },

    handleSizeChange(val) {
      this.pageDepartment.pageSize = val;
      this.initServiceDepartmentData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageDepartment.curPage = val;
      this.initServiceDepartmentData();
    },

  /* ========================= 总服务部END =========================== */
  
  /* ========================= 年度START =========================== */
    searchYearData(searchFormYear) {
      this.pageYear.curPage = 1;
      this.updateInfo(["vuexYearSearchForm", searchFormYear])
      this.initYearData(searchFormYear)
      let unit = ''
      if(this.tab_id == 0) {
        unit = '人'
      }else{
        unit = '元'
      }
      this.tableYearTitle = `<span>${this.titleSchoolName}</span> <span style="margin-left: 10px;">${this.searchFormYear.financialYear}学年目标业绩</span> <span style="margin-left: 10px;">单位 : ${unit}</span>`
    },
    queryAllCourseType() {
      this.post({
        API: 'queryAllCourseType',
        data: {}
      }).then(res => {
        this.courseList = res
      }).catch(err => {
        this.$message.error(err);
      })
    },
    changeCourse(e) {
      this.searchFormYear.productId = ''
      this.searchFormMonthly.productId = '';
      this.formGet({
        API: 'queryProductByCourseId',
        data: {
          courseId: e
        }
      }).then(res => {
        this.searchFormProductList = res
      }).catch(err => {
        this.$message.error(err);
      })
    },
    initYearData(searchForm) {
      let searchValue = searchForm || this.searchFormYear || '';
      let data = {};
      Object.assign(data, searchValue)
      data.curPage = this.pageYear.curPage;
      data.pageSize = this.pageYear.pageSize;
      // data.schoolId = data.schoolIdList.join(',')
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;
      if(data.schoolId == '') {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId)
        });
        data.schoolId = arr;
        // data.schoolId = '';
      }else{
        data.schoolId = []
        data.schoolId.push(this.searchFormYear.schoolId)
      }

      this.post({
        API: 'selectBmTargetYearPageList',
        data: data
      }).then(res => {
        this.tableDataYear = res.data;

        if(this.tab_id !== 2) {
          this.tableDataYear.forEach((item, index) => {     // 处理 数据
            
            item.bmTargetYearChildList.forEach(monthItem => {
              if(this.tab_id == 0) {
                item[monthItem.month] = monthItem.monthTargetNumber
              }else{
                item[monthItem.month] = monthItem.monthTargetPrice
              }
            })
          })
        }else{
          console.log(res);
        }

        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '年度') {
            item.children.forEach(childItem => {
              if(childItem.label == '新增') {
                this.powerList.yearAdd.show = 1
                this.powerList.yearAdd.menuId = childItem.menuId
              }
            })
          }
        })
        this.pageYear = res.page;
        
      }).catch(err => {
        this.$message.error(err);
      })
    },
    showPopupYear(formName) {
      this.$refs.yearRules.resetFields();   // 初始化
      this.tableDataAdd = []
      this.popupState = {
        showStatusYear: true,
        popupNameYear: '新建年度目标',
      }
      let btnId = this.powerList.yearAdd.menuId;
      this.initSchoolList(btnId);
    },

    clickTab(index) {
      this.tab_id = index;
      if(index == 0) {
        this.tableYearTitle = '单位 : 人'
      }else if(index == 1) {
        this.tableYearTitle = '单位 : 元'
      }else{
        this.tableYearTitle = ''
      }

      this.initYearData();

      
    },
    clickYearTab(index) {
      this.year_tab_id = index;
      
      
      this.tableDataPeople.forEach((item, index) => {
        console.log(item)
        this.tableDataPeople[index].productId = item.productId
      })
    },
    

    // 更改 学年
    changeYear(e) {
      console.log(e)

      this.tableHeadAdd.data = [
        {
          name: "课程产品名称",
          key: "productId",
          align: 'center',
          type: 'el-select',
          width: '200px',
          fixed: true,
          options: this.productList
        },
      ];

      let month = {
        name: ['9月', '10月', '11月', '12月', '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月',],
        peoplekey: ['sep', 'oct', 'nov', 'dec', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', ],
        MoneyKey: ['sep', 'oct', 'nov', 'dec', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', ],
      }
      
      for(let i=0; i<month.name.length; i++) {
        let monthName
        let width
        if(i == 0) {
          monthName = `${e}年${month.name[i]}`;
          width = '110px';
        }else if(i == 4) {
          monthName = `${Number(e)+1}年${month.name[i]}`;
          width = '110px';
        }else{
          monthName = month.name[i];
          width = '80px';
        }

        let key;
        key = month.peoplekey[i]

        let obj = {
          name: monthName,
          key: key,
          align: 'center',
          type: 'el-input',
          width: width,
          index: i,
        }

        let monthObj = {
          name: monthName,
          key: key,
          align: 'center',
          width: width,
          index: i,
          children: [
            {
              name: "人次",
              key: "monthTargetNumber",
              align: 'center',
              type: 'el-input'
            },
            {
              name: "金额",
              key: "monthTargetPrice",
              align: 'center',
              type: 'el-input'  
            },
          ]
        }
        
        this.tableHeadAdd.data.push(monthObj)
        
      }

      let tableDataAddObj = [
        {
          productId: '',
          sep: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 0,
          },
          oct: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 1,
          },
          nov: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 2,
          },
          dec: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 3,
          },
          jan: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 4,
          },
          feb: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 5,
          },
          mar: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 6,
          },
          apr: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 7,
          },
          may: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 8,
          },
          jun: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 9,
          },
          jul: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 10,
          },
          aug: {
            monthTargetNumber: '0',
            monthTargetPrice: '0',
            sort: 11,
          }, 
        },
      ]

      this.tableDataAdd= tableDataAddObj
    },

    transformData() {
      let data = []
      
      this.tableDataAdd.forEach((item, index) => {
        let obj = {
          schoolId: this.formDataYear.schoolId,
          schoolName: this.schoolName,
          financialYear: this.formDataYear.financialYear,
          productId: '',
          bmTargetYearChildList: [
          ]
        }
        data.push(obj);

        console.log(data);
        for(let i in item) {
          let monthObj = {
            month: i,
            monthTargetNumber: item[i].monthTargetNumber,
            monthTargetPrice: item[i].monthTargetPrice,
            sort: item[i].sort,
          }
          if(i !== 'productId' && i!== 'targetYearChildId') {
            data[index].bmTargetYearChildList.push(monthObj)
          }
          data[index].productId = item.productId;
        }
      })

      return data;
    },

    submitAddYear() {
      // console.log(this.tableDataPeople)
      // console.log(this.tableDataMoney)


      
      let data = this.transformData();
      

      // console.log(data);

      for(let i=0; i<data.length; i++) {
        // if(data[i].productId == '') {
        //   this.$message.error('请选择课程');
        //   return false;
        // }

        let monthData = data[i].bmTargetYearChildList
        for(let j=0; j<monthData.length; j++) {
          if(monthData[j].monthTargetNumber == '') {
            this.$message.error('请按月度填写目标人次');
            return false;
          }else{
            if(data[i].productId == '') {
              this.$message.error('请选择课程');
              return false;
            }
          }
          if(monthData[j].monthTargetPrice == '') {
            this.$message.error('请按月度填写目标金额');
            return false;
          }else{
            if(data[i].productId == '') {
              this.$message.error('请选择课程');
              return false;
            }
          }
        }
      }

      this.post({
        API: 'insertYear',
        data: {
          insertBmTargetYearList: data
        }
      }).then(res => {
        if(res == 1) {
          this.$message.success('新增成功');
          this.popupState.showStatusYear = false;
          this.initYearData();
        }
      }).catch(err => {
        this.$message.error(err);
      })
      


    },

    addProduct() {
      if(!this.formDataYear.financialYear) {
        this.$message.error('请先选择学年')
        return false;
      }

      let addObj = {
        productId: '',
        sep: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 0,
        },
        oct: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 1,
        },
        nov: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 2,
        },
        dec: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 3,
        },
        jan: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 4,
        },
        feb: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 5,
        },
        mar: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 6,
        },
        apr: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 7,
        },
        may: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 8,
        },
        jun: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 9,
        },
        jul: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 10,
        },
        aug: {
          monthTargetNumber: '0',
          monthTargetPrice: '0',
          sort: 11,
        }, 
      }

      this.tableDataAdd.push(addObj)
    },

    // 编辑 回显
    tableEditYear(rowData) {

      let btnId = this.powerList.yearAdd.menuId;
      this.initSchoolList(btnId);
      this.formGet({
        API: 'selectByIdYear',
        data: {
          id: rowData.row.targetYearId
        }
      }).then(res => {
        this.formDataYear.financialYear = res.financialYear
        this.formDataYear.schoolId = res.schoolId

        this.changeYear(this.formDataYear.financialYear)    // 编辑 生成表格
        this.showAddProduct = false;  // 隐藏 添加按钮

        // console.log(res);
        // console.log(this.tableDataPeople[0])
        let productId = res.productId;
        let targetYearId = res.targetYearId;
        console.log(res.bmTargetYearChildList);

        // sep: {
        //     monthTargetNumber: '10',
        //     monthTargetPrice: '20',
        //     sort: 0,
        //   },

        res.bmTargetYearChildList.forEach(item => {

          this.targetYearChildId[item.month] = item.targetYearChildId
          
          for(let i in this.tableDataAdd[0]) {
            // this.tableDataAdd[0][item.month] = item.monthTargetNumber
            this.tableDataAdd[0][item.month] = {
              monthTargetNumber: item.monthTargetNumber,
              monthTargetPrice: item.monthTargetPrice,
              sort: item.sort,
            }
            this.tableDataAdd[0].targetYearChildId = item.targetYearChildId
            // this.tableDataAdd[0].targetYearId = targetYearId

            this.tableDataAdd[0].productId = productId
          }
        })
        
        console.log(this.tableDataAdd[0]);
        // this.tableDataPeople[0].productId = res.productId
        this.targetYearId = res.targetYearId
        // console.log(this.tableDataMoney[0])
        this.popupState = {
          showStatusYear: true,
          popupNameYear: '编辑年度目标',
        }
      }).catch(err => {
          this.$message.error(err);
        })
    },

    submitEditYearPeople() {
      let data = this.transformData('update');


      console.log(data)
      let item = data[0].bmTargetYearChildList
      for(let i=0; i<item.length; i++) {
        if(item[i].monthTargetNumber == '') {
          this.$message.error('月度目标人次不得为空')
          return false;
        }

        if(item[i].monthTargetPrice == '') {
          this.$message.error('月度目标金额不得为空')
          return false;
        }
      }

      data[0].targetYearId = this.targetYearId;
      data[0].dataId = this.targetYearId;
      // data[0]
      console.log(data[0].bmTargetYearChildList)
      data[0].bmTargetYearChildList.forEach(item => {
        // console.log(item)
        item.targetYearId = this.targetYearId
        item.targetYearChildId = this.targetYearChildId[item.month]
      })

      this.post({
        API: 'updateYear',
        data: {
          updateBmTargetYearList: data,
          dataId: this.targetYearId
        }
      }).then(res => {
        if(res == 1) {
          this.$message.success('修改成功');
          this.popupState.showStatusYear = false;
          this.initYearData();
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    handleSizeChangeYear(val) {
      this.pageYear.pageSize = val;
      this.initYearData();
    },
    handleCurrentChangeYear(val) {
      // console.log(`当前页: ${val}`);
      this.pageYear.curPage = val;
      this.initYearData();
    },

  /* ========================= 年度END =========================== */


  /* ========================= 月度START =========================== */
    searchMonthData(searchFormMonth) {
      this.pageMonth.curPage = 1;
      
      this.updateInfo(["vuexMonthSearchForm", searchFormMonth])
      this.initMonthData(searchFormMonth)
    },
    initMonthData(searchForm) {
      let searchValue = searchForm || this.searchFormMonthly || '';
      let data = {};
      Object.assign(data, searchValue)
      data.curPage = this.pageMonth.curPage;
      data.pageSize = this.pageMonth.pageSize;
      // data.schoolId = data.schoolIdList.join(',')
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;
      
      if(data.schoolId == '') {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId)
        });
        data.schoolId = arr;
        // data.schoolId = '';
      }else{
        data.schoolId = []
        data.schoolId.push(this.searchFormMonthly.schoolId)
      }

      
      this.changeMonthSchool(this.searchFormMonthly.schoolId, true, 'all');
      
      this.post({
        API: 'selectBmTargetMonthPageList',
        data: data
      }).then(res => {
        
        // this.tableDataMonth = res.data;

        if(res.data.length > 0) {
          this.maxWeekNum = res.data[0].bmTargetMonthChildList.length;
          console.log(this.maxWeekNum)
          this.tableDataMonth = this.transformMonthData(res.data)

          console.log(this.tableDataMonth);
          let totalObj = {
            personName: '合计',
            productName: "N/A",
            schoolName: "N/A",
            workNo: "N/A",
            isTotal: 0,
            subtotal: {
              auditionNumber: 0,
              earnestNumber: 0,
              earnestPrice: 0,
              effectiveSingular: 0,
              fullNumber: 0,
              fullPrice: 0,
              weekTargetPrice: 0,
            },
            week: {
              auditionNumber: 0,
              earnestNumber: 0,
              earnestPrice: 0,
              effectiveSingular: 0,
              fullNumber: 0,
              fullPrice: 0,
              weekTargetPrice: 0,
            }
          }

          this.tableDataMonth.forEach(item => {
            totalObj.subtotal.auditionNumber += Number(item.subtotal.auditionNumber)
            totalObj.subtotal.earnestNumber += Number(item.subtotal.earnestNumber)
            totalObj.subtotal.earnestPrice += Number(item.subtotal.earnestPrice)
            totalObj.subtotal.effectiveSingular += Number(item.subtotal.effectiveSingular)
            totalObj.subtotal.fullNumber += Number(item.subtotal.fullNumber)
            totalObj.subtotal.fullPrice += Number(item.subtotal.fullPrice)
            totalObj.subtotal.weekTargetPrice += Number(item.subtotal.weekTargetPrice)

            totalObj.week.auditionNumber += Number(item.week.auditionNumber)
            totalObj.week.earnestNumber +=  Number(item.week.earnestNumber)
            totalObj.week.earnestPrice +=  Number(item.week.earnestPrice)
            totalObj.week.effectiveSingular +=  Number(item.week.effectiveSingular)
            totalObj.week.fullNumber +=  Number(item.week.fullNumber)
            totalObj.week.fullPrice +=  Number(item.week.fullPrice)
            totalObj.week.weekTargetPrice +=  Number(item.week.weekTargetPrice)
          })

          this.tableDataMonth.push(totalObj);
          

          
        }else{
          this.tableDataMonth = [];
        }



        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '月度') {
            item.children.forEach(childItem => {
              if(childItem.label == '新增') {
                this.powerList.monthAdd.show = 1
                this.powerList.monthAdd.menuId = childItem.menuId
              }
            })
          }
        })
        this.pageMonth = res.page;
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 新增月度弹窗 完成 刷新列表
    updateMonthData() {
      this.initMonthData();
    },
    updateMonthStatusNum(val) {
      this.isUpdateMonth = 0;
    },

    transformMonthData(data) {
      console.log('aaaa')
      let monthData = [];
      data.forEach((item,index) => {
        let obj = {
          personName: item.employeesName,
          workNo: item.workNo,
          schoolName: item.schoolName,
          targetMonthId: item.targetMonthId,
          week: {
            weekTargetPrice: '',
            fullPrice: '',
            fullNumber: '',
            earnestPrice: '',
            earnestNumber: '',
            auditionNumber: '',
            effectiveSingular: '',
          },
          subtotal: item.subtotal,
          productName: item.productName
        };

        console.log('bbbb')
        
        obj.week = {
          weekTargetPrice: item.bmTargetMonthChildList[this.showMonthWeekData].weekTargetPrice || 0,
          fullPrice: '' || 0,
          fullNumber: item.bmTargetMonthChildList[this.showMonthWeekData].fullNumber || 0,
          earnestPrice: '' || 0,
          earnestNumber: item.bmTargetMonthChildList[this.showMonthWeekData].earnestNumber || 0,
          auditionNumber: item.bmTargetMonthChildList[this.showMonthWeekData].auditionNumber || 0,
          effectiveSingular: item.bmTargetMonthChildList[this.showMonthWeekData].effectiveSingular || 0,
        };


        monthData.push(obj)
      })

      return monthData;

    },


    showPopupMonth(formName) {
       // 新建清空月度数据
      console.log('aaaa')
      let data = JSON.parse(sessionStorage.getItem('monthTargetData'))
      if(data) {
        this.formDataMonth = data;
      }else{
        this.formDataMonth = {
          schoolId: '',
          financialYear: '',
          financialMonth: '',
          periodsList: [
            // 每一期
            {
              periodsItem: [ 
              ],
            },
          ]
        } 
      }

      // let btnId = this.powerList.monthAdd.menuId;
      // this.initSchoolList(btnId)
      // this.isAdd ++;
      this.popupState = {
        showStatusMonthly: true,
        popupNameMonthly: '新建月度目标',
      }
    },

    tableEditMonth(rowData) {  // 编辑回显

      this.formGet({
        API: 'selectByIdMonth',
        data: {
          id: rowData.row.targetMonthId
        }
      }).then(res => {
        this.formDataMonth = res;
        this.isUpdateMonth ++;
        this.popupState = {
          showStatusMonthly: true,
          popupNameMonthly: '编辑月度目标',
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },
    tableDeleteMonth(rowData) {
      console.log(rowData.row)
      this.$confirm('是否删除该条信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: {
            id: rowData.row.targetMonthId,
            dataId: rowData.row.targetMonthId,
          }
        }).then(res => {
          this.$message.success('删除成功');
          this.initMonthData();
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });


      
    },



    changeMonthSchool(e, bool, type) {
      
      console.log('aaaaa')
      this.schoolList.forEach(item => {
        if(item.schoolId == e) {
          this.schoolName = item.schoolName;
        }
      })

      // if(!bool && this.formDataMonth.insertBmTargetMonthList[0]) {
      //   this.formDataMonth.insertBmTargetMonthList[0].employeesId = ''
      // }
      console.log('bbbb')
      let positionCode
      if(type == 'all') {
        positionCode = []
      }else{
        positionCode = [2, 5]
      }
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: positionCode,
          // positionCode: '',
          schoolId: e,
        }
      }).then(res => {
      console.log('ccc')
        this.personList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    prevWeek() {
      if(this.showMonthWeekData == 0) {
        return false
      }
      this.showMonthWeekData --;
      this.initMonthData();
    },
    nextWeek() {
      if(this.showMonthWeekData == this.maxWeekNum - 1) {
        return false
      }
      this.showMonthWeekData ++;
      this.initMonthData();
    },

    
    handleSizeChangeMonth(val) {
      this.pageMonth.pageSize = val;
      this.initMonthData();
    },
    handleCurrentChangeMonth(val) {
      // console.log(`当前页: ${val}`);
      this.pageMonth.curPage = val;
      this.initMonthData();
    },
  /* ========================= 月度END =========================== */


  },
  computed: {
    ...mapState([
      "selectProductId",
      "vuexDepartmentSearchForm",
      "vuexYearSearchForm",
      "vuexMonthSearchForm",
    ]),

    computedYear(e) {
      let year = '';
      if(this.activeName == 'serviceDepartment') {
        year = Number(this.searchFormServiceDepartment.financialYear)
        if(this.popupState.showStatusService) {
          year = Number(this.formDataServiceDepartment.financialYear)
        }
      }else if (this.activeName == 'year') {
        if(this.popupState.showStatusYear) {
          year = Number(this.formDataYear.financialYear)
        }else{
          year = Number(this.searchFormYear.financialYear)
        }
      }

      // if() {
      //   year = Number(this.formDataServiceDepartment.financialYear)
      // }
      return `${year}年9月 - ${year+1}年8月`
    },

    
    
  },
  components: {
    adminTable,
    eidtTable,
    monthPopup,
  },
}

</script>